<template>
  <div class="loginWrap">
    <!-- 头部 -->
    <app-headers></app-headers>
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <div class="contentbox">
        <van-field
          v-model="username"
          name="username"
          label="用户名："
          placeholder="请输入用户名"
          :rules="[
            { required: true, message: '请填写用户名' } //validator:
          ]"
        />
        <van-field
          class="password"
          v-model="password"
          :type="type"
          name="password"
          label="密码："
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <span class="showhide-icon">
          <b :class="showhide" @click="pswChange"></b>
        </span>
        <van-field
          class="code"
          v-model="code"
          type="text"
          name="验证码"
          placeholder="请输入验证码"
          :rules="[
            {
              trigger: 'onChange',
              validator: cheeckCord,
              required: false,
              message: '请填写验证码'
            }
          ]"
        />
        <span class="getcode" @click="testCode(4)">
          <app-sidentify :identifyCode="identifyCode"></app-sidentify>
        </span>
      </div>
      <!-- 下半部分 -->
      <div class="bottombox">
        <span class="msgreply"> {{ msgreply }}</span>
        <div class="info">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            :disabled="
              $data.codeIslock == true &&
              $data.username != false &&
              $data.password != false
                ? false
                : true
            "
            >登陆</van-button
          >
        </div>
        <van-checkbox v-model="checked" checked-color="#D70057"
          >七天内免登陆</van-checkbox
        >
        <van-row type="flex" justify="space-around">
          <van-col span="12">
            <router-link to="###">忘记密码？</router-link>
          </van-col>
          <van-col span="12" style="text-align:right">
            <router-link to="/reg">快速注册</router-link>
          </van-col>
        </van-row>
      </div>
    </van-form>
  </div>
</template>

<script>
import appSidentify from "../components/identifyCode";
import appHeaders from "../components/headers";
import usersApi from "../api/userApi.js";
import { setToken, setUser } from "../utils/auth.js";

export default {
  data() {
    return {
      username: "",
      password: "",
      checked: false, //七天免登陆
      code: "", //输入的验证码
      identifyCode: "", //图片验证码
      codeIslock: false, //验证码正确才可登录
      type: "password", //默认password
      showhide: "hide", //密码图片默认隐藏
      msgreply: "" //正则提示信息
    };
  },
  methods: {
    //提交表单 登录功能
    onSubmit(values) {
      this.password = "";
      this.code = "";
      // 发送完关锁
      this.codeIslock = false;
      // 登录更新验证码
      this.testCode(4);
      // 使用ms5加密登录，这样才能与注册匹配；
      let encryptPassword = this.$md5(values.password);
      // 发请求
      usersApi
        .login(values.username, encryptPassword)
        .then(res => {
          if (res.data.code) {
            // 发送请求成功，判断是否需要保持7天；
            if (this.checked) {
              //保存7天
              setToken(res.data.token, 7);
              setUser(values.username, 7);
            } else {
              //会话级别:关掉浏览器就没有了
              setToken(res.data.token);
              setUser(values.username);
            }
            // 轻提示
            this.mounted(res.data.message);
            this.$router.push({ name: "user" });
          } else {
            this.msgreply = res.data.message;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 轻提示，显示登录成功
    mounted(val) {
      this.$toast(val);
    },

    // 密码可见与否
    pswChange() {
      if (this.showhide == "hide") {
        this.type = "text";
        this.showhide = "show";
      } else {
        this.type = "password";
        this.showhide = "hide";
      }
    },

    // 生成验证码
    testCode(n) {
      var arr = [];
      for (var i = 0; i < n; i++) {
        var num = parseInt(Math.random() * 10);
        if (num >= 0 && num <= 9) {
          arr.push(num);
        }
        // else if ((num >= 97 && num <= 122) || (num >= 65 && num <= 90)) {
        //   arr.push(String.fromCharCode(num));
        // }
        else {
          i--;
        }
      }
      return (this.identifyCode = arr.join(""));
    },

    // 验证验证码
    cheeckCord() {
      if (this.code.length >= 4) {
        if (this.code.toLowerCase() !== this.identifyCode.toLowerCase()) {
          this.msgreply = "请输入正确的验证码。";
          this.codeIslock = false;
        } else {
          this.msgreply = "";
          this.codeIslock = true;
        }
      } else {
        this.msgreply = "";
        this.codeIslock = false;
      }
    }
  },

  components: {
    appHeaders,
    appSidentify
  },

  created() {
    // 页面刷新获取验证码
    this.testCode(4);

    // 从注册页面过来的，免输入用户名
    this.username = this.$route.query.username;
  }
};
</script>

<style scoped lang='scss'>
@import "@/assets/sass/common.scss";
@import "@/assets/sass/vw.scss";

.van-form {
  width: 100%;
  height: v(607);
  padding-top: v(10);
  background-color: #eee;
}

.contentbox {
  padding: 0 v(20);
  position: relative;
  background: white;
  .van-field {
    height: v(45);
    font-size: v(16);
    line-height: v(45);
  }
  .password {
    width: v(270);
  }
  .code {
    width: v(250);
  }
  .showhide-icon {
    display: block;
    position: absolute;
    top: v(45);
    right: 0;
    width: v(50);
    height: v(45);
    background-color: #fff;
    z-index: 3;
    .hide {
      display: block;
      margin: v(13.5) 0 0 v(16);
      width: v(18);
      height: v(18);
      background: url("/img/elf_pic.png") v(-170) v(-0) no-repeat;
      background-size: v(250) v(250);
    }
    .show {
      display: block;
      margin: v(13.5) 0 0 v(16);
      width: v(18);
      height: v(18);
      background: url("/img/elf_pic.png") v(-170) v(-23) no-repeat;
      background-size: v(250) v(250);
    }
  }
  .getcode {
    display: block;
    position: absolute;
    top: v(96);
    right: v(10);
    width: v(103);
    height: v(45);
    // background-color: #58bc58;
    z-index: 3;
  }
}

.bottombox {
  padding: 0 vw(20);
  font-size: v(14);
  color: #444;
  line-height: v(20);
  .msgreply {
    display: block;
    line-height: v(30);
    margin-bottom: v(10);
    color: #ef3d2d;
    font-size: v(14);
  }
  .info {
    margin: 0 v(10);
    height: v(50);
    .van-button {
      margin-top: v(15);
      background: #d70057;
      height: v(35);
    }
  }
  .van-checkbox {
    font-size: v(14);
  }
  .van-checkbox {
    padding-left: v(8);
  }
  .van-row {
    padding: v(25) v(10) 0 v(10);
  }
}
</style>